package com.example.backed.service.impl;

import com.example.backed.dto.UserUpdateRequest;
import com.example.backed.entity.Role;
import com.example.backed.entity.User;
import com.example.backed.mapper.RoleMapper;
import com.example.backed.mapper.UserMapper;
import com.example.backed.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Random;

@Service
@RequiredArgsConstructor
@Slf4j
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;
    private final RoleMapper roleMapper;
    private final PasswordEncoder passwordEncoder;
    
    private static final int DEFAULT_PASSWORD_LENGTH = 8;

    @Override
    public List<User> getUserList(int page, int size, String query, String role, String status) {
        log.info("查询用户列表: page={}, size={}, query={}, role={}, status={}", page, size, query, role, status);
        int offset = page * size;
        return userMapper.findAll(offset, size, query, role, status);
    }
    
    @Override
    public int countUsers(String query, String role, String status) {
        log.info("查询用户总数: query={}, role={}, status={}", query, role, status);
        return userMapper.countAll(query, role, status);
    }

    @Override
    @Transactional
    public User updateUser(Long id, UserUpdateRequest request) {
        log.info("更新用户: id={}, request={}", id, request);
        
        // 查询用户
        User user = userMapper.findById(id);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 更新用户信息
        if (request.getEmail() != null) {
            user.setEmail(request.getEmail());
        }
        if (request.getPhone() != null) {
            user.setPhone(request.getPhone());
        }
        if (request.getEnabled() != null) {
            user.setStatus(request.getEnabled() ? 1 : 0);
        }
        
        userMapper.update(user);
        
        // 更新用户角色
        if (request.getRoleNames() != null && !request.getRoleNames().isEmpty()) {
            // 删除现有角色
            userMapper.deleteUserRoles(id);
            
            // 添加新角色
            for (String roleName : request.getRoleNames()) {
                Role role = roleMapper.findByCode(roleName);
                if (role != null) {
                    userMapper.insertUserRole(id, role.getId());
                }
            }
        }
        
        // 重新查询用户信息(包括角色)
        return userMapper.findById(id);
    }

    @Override
    @Transactional
    public User updateUserStatus(Long id, boolean enabled) {
        log.info("更新用户状态: id={}, enabled={}", id, enabled);
        
        // 查询用户
        User user = userMapper.findById(id);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 更新状态
        int status = enabled ? 1 : 0;
        userMapper.updateStatus(id, status);
        
        // 重新查询用户信息
        return userMapper.findById(id);
    }

    @Override
    @Transactional
    public String resetPassword(Long id) {
        log.info("重置用户密码: id={}", id);
        
        // 查询用户
        User user = userMapper.findById(id);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 生成随机密码
        String newPassword = generateRandomPassword(DEFAULT_PASSWORD_LENGTH);
        String encodedPassword = passwordEncoder.encode(newPassword);
        
        // 更新密码
        userMapper.updatePassword(id, encodedPassword);
        
        return newPassword;
    }
    
    /**
     * 生成随机密码
     * 
     * @param length 密码长度
     * @return 随机密码
     */
    private String generateRandomPassword(int length) {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(chars.length());
            sb.append(chars.charAt(index));
        }
        
        return sb.toString();
    }
} 